//
//  MHRecentMessageViewModel.m
//  MiaoCircle
//
//  Created by 许正荣 on 2018/5/30.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHRecentMessageViewModel.h"
#import "MHRecentMessageItemViewModel.h"
#import "MHMomentDetailViewModel.h"
#import "MHIMMessageTransferHelper.h"


@interface MHRecentMessageViewModel()

@end

@implementation MHRecentMessageViewModel

-(void)initialize
{
    [super initialize];
    self.title = @"与我相关";
    self.shouldPullUpToLoadMore = YES;
    /// 没有数据时，隐藏底部刷新控件
    self.shouldEndRefreshingWithNoMoreData = NO;
    
    @weakify(self);
    RAC(self, recentMessages) = self.requestRemoteDataCommand.executionSignals.switchToLatest;
    /// 数据源
    RAC(self,dataSource) = [RACObserve(self, recentMessages) map:^(NSArray * recentMessages) {
        @strongify(self)
        return [self dataSourceWithRecentMessages:recentMessages];
    }];
    
    self.didSelectCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self);
        NSIndexPath *indexPath = input;
        MHMessageNotification *message =  self.recentMessages[indexPath.row];
        if(message.vedioObj)
        {
          return  [[[self.services.client getRecentInfoByNewVideoWithRecentId:message.recentId] mh_parsedResults] doNext:^(MHAwemeModel *model) {
                MHAwemeListViewModel *viewModel = [[MHAwemeListViewModel alloc] initWithServices:self.services params:@{MHViewModelUtilKey:@[model],@"MHViewModelShowEnterBtn":@false,@"MHViewModelShowSingleVideo":@true}];
                [self.services pushViewModel:viewModel animated:YES];
            }];
        }else
        {
            MHMomentDetailViewModel *detail = [[MHMomentDetailViewModel alloc] initWithServices:self.services params:@{MHViewModelIDKey:@(message.recentId),MHViewModelIsDetail:@(true)}];
            detail.isRealateToMe = YES;
            detail.message = message;
            detail.messageType = message.type;
            [self.services pushViewModel:detail animated:YES];
        }
        return [RACSignal empty];
    }];
    [[MHNotificationCenter rac_addObserverForName:MHRefreshRealthToMeNotification object:nil] subscribeNext:^(NSNotification * note) {
        /// 这里切换根控制器
        @strongify(self);
        if ([note.object isKindOfClass:[MHMessageNotification class]]) {
            MHMessageNotification *message =  note.object;
            NSMutableArray *recentMessages =  [self.recentMessages mutableCopy];
            [recentMessages prependObject:message];
            self.recentMessages = [recentMessages copy];
        }
    }];

}

-(instancetype)initWithServices:(id<MHViewModelServices>)services params:(NSDictionary *)params
{
    if (self = [super initWithServices:services params:params]) {
        self.isTemp = [params[@"isTemp"] integerValue];
//        self.info = params[MHViewModelUtilKey];
    }
    return self;
}


- (RACSignal *)requestRemoteDataSignalWithPage:(NSUInteger)page{
    if (self.isTemp) {
        self.recentMessages = [[[MHIMMessageTransferHelper sharedInstance] fetchChatIMMessageWithName:NSStringFromClass([MHMessageNotification class])] mutableCopy];
        [[MHIMMessageTransferHelper sharedInstance] resetAllreadWithKey:NSStringFromClass([MHMessageNotification class])];
        return [RACSignal empty];
    }else
    {
        
        NSArray * (^mapRepeaters)(NSArray *) = ^(NSArray *recentMessages) {
            [[MHIMMessageTransferHelper sharedInstance] resetAllreadWithKey:NSStringFromClass([MHMessageNotification class])];
            if (page == 1) {
                /// 下拉刷新
            } else {
                /// 上拉加载
                recentMessages = @[(self.recentMessages ?: @[]).rac_sequence, recentMessages.rac_sequence].rac_sequence.flatten.array;
            }
            return recentMessages;
        };
        
        return [[[self.services.client getRecentNotificationPagedListPageNum:page pageSize:self.perPage] mh_parsedResults] map:mapRepeaters];
    }
    
    
}

#pragma mark - 辅助方法
- (NSArray *)dataSourceWithRecentMessages:(NSArray *)recentMessages {
        if (MHObjectIsNil(recentMessages) || recentMessages.count == 0) return @[];
        NSMutableArray *viewModels = [[recentMessages.rac_sequence map:^(MHMessageNotification *recentMessage) {
            MHRecentMessageItemViewModel *viewModel = [[MHRecentMessageItemViewModel alloc] initWithModel:recentMessage];
            return viewModel;
        }].array mutableCopy];
        return viewModels ?: @[] ;
}
@end
